package com.zx.auth.block.service.impl;

import com.zx.auth.block.mapstruct.OAuth2AuthorizationMapStructMapper;
import com.zx.auth.block.modle.OAuth2Authorization;
import com.zx.auth.block.param.OAuth2AuthorizationParam;
import com.zx.auth.block.repository.OAuth2AuthorizationRepository;
import com.zx.auth.block.repository.custom.OAuth2AuthorizationCustomRepository;
import com.zx.auth.block.service.IOAuth2AuthorizationService;
import com.zx.auth.block.vo.OAuth2AuthorizationVO;
import com.zx.core.context.TenantContextHolder;
import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * OAuth2授权管理服务实现类
 * 实现OAuth2授权的业务逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OAuth2AuthorizationServiceImpl implements IOAuth2AuthorizationService {

    private final OAuth2AuthorizationRepository authorizationRepository;
    private final OAuth2AuthorizationCustomRepository authorizationCustomRepository;

    /**
     * 根据ID获取OAuth2授权信息
     *
     * @param id 授权ID
     * @return 授权信息
     */
    @Override
    public ObjectWrapper<OAuth2AuthorizationVO> getAuthorizationById(String id) {
        ObjectWrapper<OAuth2AuthorizationVO> result = new ObjectWrapper<>();
        try {
            // 查询授权信息
            Optional<OAuth2Authorization> authorizationOptional = authorizationRepository.findById(id);
            if (authorizationOptional.isPresent()) {
                // 转换为VO对象
                OAuth2AuthorizationVO authorizationVO = OAuth2AuthorizationMapStructMapper.INSTANCE.authorizationToAuthorizationVO(authorizationOptional.get());
                result.setData(authorizationVO);
            }
        } catch (Exception e) {
            log.error("获取授权信息时发生错误", e);
            result.fail("获取授权信息时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询OAuth2授权列表
     *
     * @param authorizationParam 授权参数
     * @return 授权列表
     */
    @Override
    public PageWrapper<OAuth2AuthorizationVO> listAuthorizations(OAuth2AuthorizationParam authorizationParam) {
        PageWrapper<OAuth2AuthorizationVO> result = new PageWrapper<>();

        try {
            // 使用PageInfo帮助类处理分页计算，统一项目中的分页处理逻辑
            PageInfo pageInfo = new PageInfo(authorizationParam.getPageNum(), authorizationParam.getPageSize());

            // 创建分页对象
            Pageable pageable = PageRequest.of(
                    pageInfo.getPageNum().intValue(),
                    pageInfo.getPageSize().intValue()
            );

            // 使用自定义仓库进行分页查询
            Page<OAuth2Authorization> authorizationsByPage = authorizationCustomRepository.findAuthorizationsByPage(authorizationParam, pageable, TenantContextHolder.getTenantId());

            // 转换为VO对象
            List<OAuth2AuthorizationVO> voList = authorizationsByPage.getContent().stream()
                    .map(OAuth2AuthorizationMapStructMapper.INSTANCE::authorizationToAuthorizationVO)
                    .collect(Collectors.toList());

            // 设置返回结果
            result.setData(voList);
            result.setTotal(authorizationsByPage.getTotalElements());
            result.setCurrentPageNum(authorizationParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("分页查询授权时发生错误", e);
            result.fail("分页查询授权时发生错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 删除OAuth2授权
     *
     * @param id 授权ID
     * @return 删除结果
     */
    @Override
    public ResponseWrapper deleteAuthorization(String id) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 业务验证 - 查询授权是否存在
            Optional<OAuth2Authorization> authorizationOptional = authorizationRepository.findById(id);

            if (authorizationOptional.isEmpty()) {
                result.fail("授权不存在: " + id);
                return result;
            }

            // 验证租户权限 - 确保只能删除当前租户的数据
            // 虽然查询结果应该是当前租户的数据，但为了安全起见，再次验证
            OAuth2Authorization authorization = authorizationOptional.get();

            // 安全比较租户ID，防止跨租户操作
            if (!TenantContextHolder.getTenantId().equals(authorization.getTenantId())) {
                result.fail("非当前租户的数据，不能删除");
                return result;
            }

            // 删除授权
            authorizationRepository.delete(authorization);
        } catch (Exception e) {
            log.error("删除授权时发生错误", e);
            result.fail("删除授权时发生错误: " + e.getMessage());
        }
        return result;
    }
}